import React, { Component } from "react";

// 创建Context上下文
const Context = React.createContext();

export default class A extends Component {
  state = { name: "hyy" };
  render() {
    const { name } = this.state;
    return (
      <div>
        <h2>A组件</h2>
        <h4>A name = {name}</h4>
        <Context.Provider value={name}>
          <B />
        </Context.Provider>
      </div>
    );
  }
}

class B extends Component {
  render() {
    return (
      <div>
        <h2>B组件</h2>
        <C />
        <D />
      </div>
    );
  }
}

class C extends Component {
  // 声明接收
  static contextType = Context;
  render() {
    console.log("c ==> ", this.context);
    return (
      <div>
        <h2>C组件</h2>
        <h4>C name = {this.context}</h4>
      </div>
    );
  }
}

function D() {
  // 函数式组件使用Consumer的回调函数进行解析
  return (
    <div>
      <h2>D组件</h2>
      <h4>
        D name =
        <Context.Consumer>
          {(value) => {
            console.log("D :>> ", value);
            return value;
          }}
        </Context.Consumer>
      </h4>
    </div>
  );
}
